package com.ahuan.controller;

import com.ahuan.domain.Module;
import com.ahuan.exception.BusinessException;
import com.ahuan.resp.Res;
import com.ahuan.service.RoleRightService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/RoleRight")
public class RoleRightController {
    @Autowired
    RoleRightService roleRightService;

    @GetMapping("/tree/{id}")
    public Res getRightTree(@PathVariable String id) {
        List<Module> modules = null;
        try {
            log.info("获取角色权限树");
            modules = roleRightService.queryRoleRightTree(id);
            if(modules.size()==0){
                return Res.failOperate();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("获取角色权限树失败");
        }
        return Res.successOperate(modules);
    }


    @PostMapping("/save")
    public Res saveRoleRight(@RequestParam String roleId,@RequestParam List<String> moduleIds) {
        try {
            log.info("roleId:{},moduleIds:{}",roleId,moduleIds);
            for (String moduleId : moduleIds) {
                System.out.println(moduleId);
            }
            if(moduleIds.size()==0){
                //如果为空，则默认添加一个0,为清空权限
                moduleIds.add("0");
            }

            if(roleRightService.saveRoleRight(roleId,moduleIds)){
             return Res.successOperate();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("保存角色权限失败");
        }

        return Res.failOperate();
    }
}
